<template>
  <a-card :title="title" class="element-top">
    <!-- 表格标题 -->
    <template #extra>
      <a-space size="middle">
        <a-button type="primary" @click="handleAdd" v-if="enableAdd">
          <template #icon><PlusCircleOutlined /></template>
        </a-button>
        <a-button type="primary" @click="handleBatchDelete" v-if="enableDelete">
          <template #icon><CloseCircleOutlined /></template>
        </a-button>
        <a-button type="primary" @click="handleImport" v-if="enableImport">
          <template #icon><ImportOutlined /> </template>
          </a-button>
        <a-button type="primary" @click="handleExport" v-if="enableExport">
          <template #icon> <ExportOutlined /></template>
          </a-button>
        <!--其他按钮-->
        <slot name="titleBtns"></slot>
        <!--右侧工具栏-->
        <a-tooltip :title="t('lang.button.refresh')">
          <ReloadOutlined @click="handleRefresh" />
        </a-tooltip>

        <a-tooltip :title="t('lang.button.density')">
          <a-dropdown trigger="click">
            <ColumnHeightOutlined />
            <template #overlay>
              <a-menu v-model:selected-keys="_tableSize" :items="_sizeItems" @click="handleSizeChange" />
            </template>
          </a-dropdown>
        </a-tooltip>

        <a-tooltip :title="t('lang.button.columnSettings')">
          <!-- v-model:open="dropdownVisible" -->
          <a-dropdown trigger="click">
            <SettingOutlined />
            <template #overlay>
              <a-card>
                <template #title>
                  <a-checkbox v-model:checked="_checkAll" :indeterminate="_indeterminate" @change="handleCheckAllChange"> {{ t('lang.button.checkAll') }} </a-checkbox>
                </template>
                <template #extra>
                  <a-button type="link" @click="handleResetChange"> {{ t('lang.button.reset') }} </a-button>
                </template>
                <a-checkbox-group v-model:value="_checkList" :options="_options" style="display: flex; flex-direction: column" @change="handleCheckChange" />
              </a-card>
            </template>
          </a-dropdown>
        </a-tooltip>
      </a-space>
    </template>

    <a-table
      style="margin-top: 5px"
      ref="baseTableRef"
      :row-key="rowKey"
      :bordered="true"
      :row-selection="_rowSelection"
      :data-source="dataSource"
      :columns="_columns"
      :loading="loading"
      :pagination="_pagination"
      :scroll="scroll"
      @change="handleTableChange"
      :custom-row="handleCustomRow"
    >
      <!-- 行点击+展开的内容 -->
      <template #expandedRowRender v-if="enableExpandedRow">
        <slot name="expandedRowRender"></slot>
      </template>

      <!-- 自定义列：logo -->
      <template #customCell="{ column, record }">
        <template v-if="column.dataIndex === 'logo'">
          <img width="60" style="cursor: pointer" height="60" :src="record.logo" />
        </template>
        <template v-if="column.dataIndex === 'status'">
          <a-badge :status="statusTypeFilter(record.status)" :text="statusTextFilter(record.status)" />
        </template>
      </template>

      <!-- 动态插槽 -->
      <template v-for="slot in scopedSlots" #[slot]="{ text, record, index }">
        <slot :name="slot" :text="text" :record="record" :index="index"></slot>
      </template>

      <!-- 操作列 -->
      <template #bodyCell="{ column, record, index }">
        <!-- 序号列 -->
        <template v-if="column.dataIndex === 'index'">
          {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
        </template>
        <!-- 操作列 -->
        <template v-if="column.dataIndex === 'action'">
          <a-space>

            <a-button size="small" type="link" danger @click="handleDetail(record)" v-if="enableDetail">
              <FileTextTwoTone />
            </a-button>

            <a-button size="small"  type="link" danger @click="handleUpdate(record)" v-if="enableUpdate">
              <EditTwoTone />
            </a-button>

            <a-button size="small"  type="link" danger @click="handleDelete(record)" v-if="enableDelete">
              <DeleteTwoTone />
            </a-button>
           
            <slot name="buttons" :item="record"></slot>
          </a-space>
        </template>
      </template>
    </a-table>
  </a-card>
</template>

<script setup lang="ts">
import { computed, onMounted, useSlots } from 'vue'
// import { useI18n } from 'vue-i18n';
import { useBaseTable } from './baseTable'
import { statusTypeFilter, yesNoTextFilter } from '@/utils/filters'
import { ColumnHeightOutlined, PlusCircleOutlined, CloseCircleOutlined, ReloadOutlined, SettingOutlined,
   ImportOutlined, ExportOutlined,EditTwoTone,FileTextTwoTone,DeleteTwoTone} from '@ant-design/icons-vue'
// 多语言
const { t } = useI18nLocale()

// 1. 定义外部传递进来的props
const props = defineProps({
  title: {
    type: String,
    default: '',
  },
  loading: {
    type: Boolean,
    default: false,
  },
  rowKey: {
    type: [String, Function],
    default: 'id',
  },
  columns: {
    type: Array,
    required: true,
  },
  dataSource: {
    type: Array,
    required: true,
  },
  scroll: {
    type: Object,
    default: () => ({ x: 1500, y: 620 }),
  },
  enableAdd: {
    type: Boolean,
    default: true,
  },
  enableDelete: {
    type: Boolean,
    default: true,
  },
  enableUpdate: {
    type: Boolean,
    default: true,
  },
  enableDetail: {
    type: Boolean,
    default: true,
  },
  enableImport: {
    type: Boolean,
    default: true,
  },
  enableExport: {
    type: Boolean,
    default: true,
  },
  enableSelect: {
    type: Boolean,
    default: true,
  },
  enableExpandedRow: {
    type: Boolean,
    default: false,
  },
  pagination: {
    type: Object,
    default: () => ({
      hideOnSinglePage: true,
      defaultCurrent: 1,
      current: 1,
      total: 0,
      defaultPageSize: 20,
      pageSize: 20,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['20', '50', '100', '200', '500', '1000'],
      showTotal: (total: number) => `共${total}条数据`,
    }),
  },  
})

console.log('1. 外部传递的对象.props', props)

// 2. 定义定义外部传递进来的 emits 函数
const emit = defineEmits(['handleAdd', 'handleUpdate', 'handleDeleteSubmit', 'handleDetail', 'handleImport', 'handleExport', 'handleRefresh', 'handleRowClick'])
console.log('2. 外部传递的函数.emit', emit)
// 3. 将参数传递给ts内部
const table = useBaseTable(props, emit)
console.log('3. 将参数传递给ts内部.table', table)

// 4. 从table.ts中获取可使用的变量和方法
const {
  _columns,
  // _enableSelect,
  // _enableOnClick,
  // _selectedRows,
  // _selectedRowKeys,
  // _selectedTreeKeys,
  // _selectType,
  _pagination,
  _rowSelection,
  _enableOnSelectAll,
  _enableOnRowSelected,

  // 函数
  handleAdd,
  handleDelete,
  handleBatchDelete,
  handleUpdate,
  handleDetail,
  handleImport,
  handleExport,
  handleTableChange,
  handleRefresh,
  handleCustomRow,
  // 列头设置
  _tableSize,
  _sizeItems,
  _checkList,
  _checkAll,
  _indeterminate,
  _options,
  handleSizeChange,
  handleResetChange,
  handleCheckChange,
  handleCheckAllChange,
} = table
console.log('6. 从table.ts中获取可使用的变量和方法.table', table)

// 5. 动态加载动态插槽
const scopedSlots = computed(() => {
  const slots = useSlots()
  return slots ? Object.keys(slots).filter((slot) => slot !== 'expandedRowRender' && slot !== 'title') : []
})

// 6. 挂载时处理 rowSelection 的事件
onMounted(() => {
  if (table._rowSelection.value) {
    if (!table._enableOnSelectAll.value) delete table._rowSelection.value.onSelectAll
    if (!table._enableOnRowSelected.value) delete table._rowSelection.value.onSelect
  }
})

// 7. 使用 defineExpose 暴露需要被父组件访问的属性和方法。暴露需要让父组件访问的函数和对象,例如分页数据
defineExpose({ ...table })
</script>
